package com.lg.erp.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lg.erp.entity.*;
import com.lg.erp.service.IUserRoleService;
import com.lg.erp.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ligen
 * @since 2021-04-12
 */
@RestController
public class UserController {

    @Autowired
    private IUserService userService;
    @Autowired
    private IUserRoleService userRoleService;

    public String encryptPassword(String password) {
        // BCryptPasswordEncoder 加密
        return new BCryptPasswordEncoder().encode(password);
    }

    //用户分页
    @RequestMapping("/user/{current}")
    public JsonResult getUserByPage(@PathVariable Integer current){
            Page<SUser> page=new Page<>(current,10);
            IPage<SUser> pages = userService.getUserByPage(page);
            return new JsonResult(1,"ok",pages);
    }
    //用户增加
    @RequestMapping(value = "/user",method = RequestMethod.POST)
    public JsonResult saveUser(@RequestBody SUser user){
        com.lg.erp.entity.SUser one = userService.getUserByLogin();
        user.setId(UUID.randomUUID().toString().replace("-",""));
//        user.setCreateUserId(one.getId().toString());
//        user.setCreateTime(LocalDateTime.now());
        user.setPassword(encryptPassword(user.getPassword()));
        userService.save(user);
        return new JsonResult(1,"用户创建成功",user);
    }
    //用户修改
    @RequestMapping(value = "/user",method = RequestMethod.PUT)
    public JsonResult updateUser(@RequestBody SUser user){
        com.lg.erp.entity.SUser one = userService.getUserByLogin();
//        user.setUpdateUserId(one.getId().toString());
//        user.setUpdateTime(LocalDateTime.now());
        userService.updateById(user);
        return new JsonResult(1,"用户更新成功",user);
    }
    //用户删除
    @RequestMapping(value = "/user/{id}",method = RequestMethod.DELETE)
    public JsonResult deleteUser(@PathVariable String id){
        userService.removeById(id);
        List<SUserRole> list = userRoleService.list(new QueryWrapper<SUserRole>().lambda()
                .eq(SUserRole::getUserId, id));
        for (SUserRole userRole : list) {
            userRoleService.remove(new QueryWrapper<SUserRole>().lambda()
                    .eq(SUserRole::getRoleId,userRole.getRoleId())
                    .eq(SUserRole::getUserId,userRole.getUserId()))      ;
        }
        return new JsonResult(1,"用户删除成功",null);
    }
}
